from django.shortcuts import render, redirect
from webapp.models import Department, UserInfo

from webapp.uitls.pagination import Pagination
from webapp.modelforms.mymodelform import UserInfoModelForm


def user_add(request):
    if request.method == "POST":
        name = request.POST.get("name")
        password = request.POST.get("password")
        gender = request.POST.get("gender")
        account = request.POST.get("account")
        create_time = request.POST.get("create_date")
        depart = request.POST.get("depart")
        age = request.POST.get("age")
        UserInfo.objects.create(name=name, password=password, gender=gender, age=age, account=account,
                                create_time=create_time, depart_id=depart)
        return redirect("/user/list/")

    depart = Department.objects.all()
    return render(request, "user_add.html", {"depart": depart})


def user_delete(request, nid):
    UserInfo.objects.filter(id=nid).delete()
    return redirect("/user/list/")


# 2、定义一个类继承forms.ModelForm


def user_update(request, nid):
    user = UserInfo.objects.filter(id=nid).first()
    if request.method == "GET":
        form = UserInfoModelForm(instance=user)
        # 注释
        return render(request, "user_update.html", {"form": form})

    # 需要告诉form数据是哪条，所以传入instance，不然执行.save就会新增
    form = UserInfoModelForm(data=request.POST, instance=user)
    if form.is_valid():
        # 默认保存的是用户输入的内容，可以额外添加字段
        # form.instance.字段名 = 值
        form.save()
        return redirect("/user/list/")
    return render(request, "user_update.html", {"form": form})


def user_list(request):
    data = UserInfo.objects.all()
    page = Pagination(request, data, 5, 2)
    data = UserInfo.objects.filter()[page.start_number:page.end_number]
    return render(request, "user_list.html", {"data": data, 'page_list': page.page_list})


def user_model_form_add(request):
    if request.method == "GET":
        form = UserInfoModelForm()
        return render(request, "user_modelform_add.html", {"form": form})

    form = UserInfoModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/user/list/")

    return render(request, "user_modelform_add.html", {"form": form})
